import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
import { RedisService } from 'src/modules/common/services/redis.service';
import { getUserRedisKey } from '../constant/redisKey';
import { LoginUserResponseDto } from 'src/modules/auth/dto/login-user.dto';
import { AuthService } from 'src/modules/auth/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private readonly jwtService: JwtService,
    private readonly reflector: Reflector,
    private readonly redisService: RedisService,
    private readonly authService: AuthService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }

    const request = context.switchToHttp().getRequest<Request>();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException();
    }
    try {
      const payload = await this.jwtService.verifyAsync(token);
      const { id } = payload;
      const redisKey = getUserRedisKey(id);
      const redisPayloadStr = await this.redisService.get(redisKey);
      const redisPayload = JSON.parse(redisPayloadStr) as LoginUserResponseDto;
      if (!redisPayload) {
        throw new UnauthorizedException();
      }

      if (
        !(redisPayload as LoginUserResponseDto).redisEndTime ||
        (redisPayload as LoginUserResponseDto).redisEndTime < Date.now()
      ) {
        throw new UnauthorizedException();
      }

      if (
        Date.now() - (redisPayload as LoginUserResponseDto).redisEndTime <
        10 * 60 * 1000
      ) {
        // 剩余10分钟更新过期时间
        this.authService.saveUserToRedis(redisPayload as LoginUserResponseDto);
      }
      request['user'] = redisPayload;
    } catch {
      throw new UnauthorizedException();
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
